<?php

namespace App\Models\Basic;

use App\Models\BaseModel;
use Illuminate\Support\Facades\Auth;

class Dictionary extends BaseModel
{

    protected $table = 'dictionaries';
    protected $fillable = [
        'title', 'code', 'description', 'rank', 'state', 'created_by', 'updated_by', 'data_scope',
    ];
    public $sorters = ['rank'];
    public $params = ['title', 'code'];

    public function members()
    {
        return $this->hasMany('App\Models\Basic\DictionaryMember', 'dictionary_id');
    }

    /**
     * 添加字典
     * @param $data
     * @return mixed
     */
    public function addDictionary($data)
    {
        $userId = Auth::id();
        $data['created_by'] = $userId;
        $data['updated_by'] = $userId;
        $data['data_scope'] = $this->getDataScope();

        return $this->create($data);
    }

    /**
     * 编辑字典
     * @param $data
     * @param $id
     * @return null
     */
    public function editDictionary($data, $id)
    {
        $model = $this->find($id);

        if (!$model) {
            return null;
        }

        $data['updated_by'] = Auth::id();

        return $model->updateOrCreate(['id' => $id], $data);
    }

    /**
     * 获取字典全部信息
     * @return mixed
     */
    public function getDictionaryListAll()
    {
        return $this->where('state', 1)->orderBy('rank', 'asc')->get(['id', 'title', 'code']);
    }

    /**
     * 获取字典列表
     * @param $limit
     * @param $sorter
     * @param $search
     * @param $defaultSorter
     * @return mixed
     */
    public function getDictionaryList($limit, $sorter, $search, $defaultSorter)
    {
        $perPage = $limit > 0 ? $limit : $this->limit;
        if ($defaultSorter == 'asc') {
            $model = $this->orderBy('rank', $defaultSorter);
        } else {
            $model = $this->orderBy($sorter[0], $sorter[1]);
        }

        $model->select(['id', 'title', 'code', 'description', 'rank', 'state', 'created_at']);

        foreach ($search as $key => $value) {
            switch ($key) {
                case 'code':
                case 'title':
                    $model->where($key, 'like', '%' . $value . '%');
                    break;
            }
        }

        return $model->paginate($perPage)->toArray();
    }

    /**
     * 获取字典成员列表
     */
    public function getDictionaryMemberAll($code, $limit, $search, $page)
    {
        $model = DictionaryMember::select(['id', 'dictionary_id', 'title', 'code', 'parent_id'])->where('state', 1);

        $model->whereHas('dictionary', function($dictionary) use ($code) {
            $dictionary->where('code', $code);
        });

        if (isset($search)) {
            $model->where(function($where) use ($search) {
                $where->where('title', 'like' ,'%' . $search .'%')->orWhere('code', 'like', '%' . $search .'%');
            });
        }

        $data = $model->orderBy('rank', 'asc')->get()->toArray();

        if (count($data) > 0) {
            $res = $this->_setTree($data);
            $newData['current_page'] = $page;
            $newData['per_page'] = $limit > 0 ? $limit : 15;
            $newData['data'] = array_slice($res, ($page - 1) * $newData['per_page'], $newData['per_page']);
            $newData['total'] = count($res);
        } else {
            $newData['data'] = [];
            $newData['current_page'] = $page;
            $newData['total'] = 0;
            $newData['per_page'] = $limit > 0 ? $limit : 15;
        }

        return $newData;
    }

    /**
     * 生成树状结构数据
     * @param $arr
     * @return array
     */
    public function _setTree($arr)
    {
        //构造数据
        $items = [];
        foreach ($arr as $v) {
            $items[$v['id']] = $v;
        }

        //遍历数据 生成树状结构
        $tree = [];
        foreach ($items as $key => $value) {
            if (isset($items[$value['parent_id']])) {
                $items[$value['parent_id']]['children'][] = &$items[$key];
            } else {
                $tree[] = &$items[$key];
            }
        }

        return $tree;
    }
}
